package com.zjl.legendary.service.impl;

import com.alibaba.excel.EasyExcel;
import com.zjl.legendary.dao.QuestionDao;
import com.zjl.legendary.dto.QuestionDto;
import com.zjl.legendary.entity.Question;
import com.zjl.legendary.listener.QuestionReadListener;
import com.zjl.legendary.service.intf.QuestionService;
import com.zjl.legendary.util.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * @author zhoujingluo
 * @date 2021/5/27 8:37
 */
@Service
@Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.SUPPORTS,
        readOnly = true,rollbackFor = Exception.class)
public class QuestionServiceImpl implements QuestionService {
    @Autowired
    private QuestionDao questionDao;
    
    /**
     * 根据用户上传的Excel表格，向数据库中批量导入试题
     * @param source 前端传入的文件对象
     * @return 执行结果 true-执行成功 false-执行失败
     */
    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    @Override
    public boolean saveBatch(MultipartFile source, Integer uid) throws IOException {
        if (source != null && source.getSize() > 0){
            QuestionReadListener questionReadListener = new QuestionReadListener();
            questionReadListener.setUid(uid);
            questionReadListener.setQuestionDao(questionDao);
            EasyExcel.read(source.getInputStream(), Question.class,questionReadListener).sheet().doRead();
            return true;
        }
        return false;
    }

    /**
     * 查询题库中的所有试题
     * @return 试题集合
     */
    @Override
    public List<QuestionDto> query() {
        return questionDao.selectAllWithUserName();
    }

    /**
     * 根据题目关键字对试题进行模糊查询
     * @param title
     * @return
     */
    @Override
    public List<QuestionDto> query(String title) {
        return questionDao.selectByTitle(title);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    public boolean save(Question question) {
        //校验对象是否为空
        if (question != null) {
            //校验题目与答案是否为空
            if (StrUtils.isNotNull(question.getTitle(),question.getAnswer())){
                return  questionDao.insert(question)> 0;
            }
        }
        return false;
    }

    @Override
    public List<QuestionDto> query(Integer uid) {
        return questionDao.selectByUid(uid);
    }


}
